import copy
import logging
from datetime import datetime
from airflow.models.idata_env import Env
from airflow.utils.session import provide_session

log = logging.getLogger(__name__)


@provide_session
def add_env(name, env_type, etl_path, common_jar_path, kafka_jar_path, temporary_file_path, jdbc_jar_path, mongodb_jar_path,
              checkpoint_path, decoder_path, hive_jar_path, es_jar_path, binary_path, docker_image, session=None):
    env = Env(name=name, type=env_type, etl_path=etl_path, common_jar_path=common_jar_path, kafka_jar_path=kafka_jar_path,
                  temporary_file_path=temporary_file_path, jdbc_jar_path=jdbc_jar_path, mongodb_jar_path=mongodb_jar_path,
                  checkpoint_path=checkpoint_path, decoder_path=decoder_path, hive_jar_path=hive_jar_path, es_jar_path=es_jar_path,
                  binary_path=binary_path, docker_image=docker_image)
    Env.add_env(env, session)


@provide_session
def delete_env(parma_id, session=None):
    Env.delete_env(parma_id, session)


@provide_session
def get_envs(page, env_type, session=None):
    if page == 0:
        envs = Env.get_envs(env_type, session)
        map_envs = map(Env.to_json, envs)
        return list(map_envs)
    else:
        envs_result = Env.get_envs_page(page, env_type, session)
        envs_result.items = list(map(Env.to_json, envs_result.items))
        result = envs_result.to_json()
        return result


@provide_session
def update_env(env_id, name, env_type, etl_path, common_jar_path, kafka_jar_path, temporary_file_path, jdbc_jar_path, mongodb_jar_path,
                 checkpoint_path, decoder_path, hive_jar_path, es_jar_path, binary_path, docker_image, session=None):
    env = Env(id=env_id, name=name, type=env_type, etl_path=etl_path, common_jar_path=common_jar_path, kafka_jar_path=kafka_jar_path,
                  temporary_file_path=temporary_file_path, jdbc_jar_path=jdbc_jar_path, mongodb_jar_path=mongodb_jar_path,
                  checkpoint_path=checkpoint_path, decoder_path=decoder_path, hive_jar_path=hive_jar_path, es_jar_path=es_jar_path,
                  binary_path=binary_path, docker_image=docker_image)
    Env.update_env(env, session)
